import axios from 'axios'
import router from '../router'
// import store from '../store'
import service from './contactApi'
import { Message,MessageBox } from 'element-ui'
import { getToken, removeToken } from '@/utils/auth'
import {errorCode,successCode} from '@/service/httpCode'
import utils from '@/utils/utils'
// service 循环遍历输出不容的请求方法
const instance = axios.create({
    // baseURL: 'https://ctapi.phpbai.com/',//线上   api.lovepurethai.com
    // baseURL: 'https://api.lovepurethai.com/',
    baseURL: utils.data.baseURL,
    timeout: 60000
})
const Http = {} // 请求方法的容器
// 请求格式统一
for (const key in service) {
    const api = service[key]
    // async 作用：避免进入回调地狱
    Http[key] = async function( // 参数
        params, // 请求参数
        isFormData = false, // 是否是form-data请求
        config = {} // 请求配置参数
    ) {
        let newParams = {} // 为转换form-data格式
        api.config?config =  api.config : '';
        // content-type 是否试form-data的判断
        if (params && isFormData) {
            newParams = new FormData()
            for (const i in params) {
                newParams.append(i, params[i])
            }
        } else {
            newParams = params
        }
        console.log(config,'configconfigconfig');
        // 不同请求判断
        let response = {} // 请求返回值
        if (api.method === 'post' || api.method === 'put' || api.method === 'patch') {
            try {
                response = await instance[api.method](api.url, newParams, config)
            } catch (err) {
                response = err
            }
        } else if (api.method === 'get' || api.method === 'delete') {
            config.params = newParams
            try {
                response = await instance[api.method](api.url, config)
            } catch (err) {
                response = err
            }
        }
        return response // 返回响应值
    }
}

const axiosPromiseArr = []
// 请求拦截器
instance.interceptors.request.use(
    config => {
        let token = getToken() || '';
        if (token) {
            config.headers['x-access-token'] = token; //将token放到请求头发送给服务器
        }
        config.cancelToken = new axios.CancelToken(ce => {
            axiosPromiseArr.push({
                cancel:ce
            })
            if('cancelCall' in config){
                config.cancelCall(ce)
            }
        })
        // // 请求等待lodding 遮罩层
        // store.commit('loaddingShow', true)
        return config
    }, () => {
        // 清除loadding
        // store.commit('loaddingShow', false)
        Message.error('请求错误')
    }
)

// 响应拦截器
instance.interceptors.response.use(
    res => {
        if(res.status !== 200){
            Message.error(res.msg)
            return new Promise(() => {})
        }else{
            let resData = res.data
            // if(res.data.type=='application/download'){
            //     console.log(res);
            //     // var downloadUrl = window.URL.createObjectURL(res.data);//转换
            //     // var anchor = document.createElement("a");
            //     // anchor.href = downloadUrl;
            //     // anchor.download = decodeURI(res.headers['filename']);
            //     // anchor.click();
            //     return {code:true}
            // }else 
            if (!successCode[resData.code]) {
                console.log(resData,'resData');
                if(resData.msg)
                Message({
                  message: resData.msg,
                  type: 'error',
                  duration: 5 * 1000
                })
                if (resData.code >= 11101 && resData.code <= 11107 && router.app._route.path != '/login') {
                  // to re-loginvue
                  MessageBox.confirm(`${errorCode[resData.code]},需要重新登录`, '提示', {
                    confirmButtonText: '重新登录',
                    type: 'warning'
                  }).then(() => {
                    localStorage.removeItem('userInfo')
                    removeToken()
                    router.push(`/login?redirect=${router.app._route.path}`)
                  })
                }
                resData.code = false;
                return resData;
            } else {
                return resData;
            }

        }
        // 清除loadding
        // store.commit('loaddingShow', false)
    }, (error) => {
        console.log("🤬 ~ Httperror", error)
        // 清除loadding
        // store.commit('loaddingShow', false)
        // 取消请求的情况下，终端Promise调用链（判断是取消还是响应错误）
        if (axios.isCancel(error)) {
            console.log('取消请求成功')
            return new Promise(() => {})
        } else {
            Message.error('请求错误')
            return Promise.reject(error)
        }
    }
)

export default {
    Http,
    axiosPromiseArr
}